var express = require('express');
var router = express.Router();
// let AlipaySdk = require("alipay-sdk").default
// let ALipayFormData = require("alipay-sdk/lib/form").default


const {User}=require('../db/index')
// const jwt=require('jsonwebtoken');
const { sendSMS } = require('../server/smsService');
const {generateTokens,verifyToken}=require('../server/jwt')
require('dotenv').config()


// router.post("/pay", async (req, res, next) => {
//   //订单编号 付款金额  付款商品信息
//   let { orderNumber, amount, goodsInfo } = req.body
//   //实例化支付宝sdk
//   const alipaySdk = new AlipaySdk({
//     // 设置应用 ID
//     appId: '2021000147650546',
//     // 设置应用私钥
//     privateKey: "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCMLn4aNdjON8ATKqowa7GppU+znikiFWquoDYhFLDg3047YhVJDz5MMJLGX9gZ3r+yOBnI5uOrD9TA7DiDOujZar1gj/lR5Jbsf6G+sHFA6mTRuiayoz8YLNQmNBmf7ES8cCstTG83Wh55BJd7XuiwO0TpBmcOeYJH7o1p/l5sR/IbskUgAoCY3I2La8WhXOlCT63NUMqaBypRlyfHrgzytnXxe/Gj/wtDilcpXFj/dehdWtwAxRJTKrpRIu4TlnfauUfjvmcYjG0dhimNjT88jpJa6ooV2f9vjvgZI9uLo06xoVTcEkuCzusQXEEqZh1rBGs3FF5TFiwfovtL4rUjAgMBAAECggEADMjctVU93ajV+qmEdgAMZvVtrGr7Q2GCpkR0S1YQv6F+CAps+InMW7R+Xls1YT6gaweUym7MSriZ5bJlgQppXBLRDLJ0wZRAc3c8cCC1Y389DKeWieo7gd/sxUMxJxWsOydbuLjk175/UvgpPJYuUIxHP51W3soUKK1H9me9gtB1QDaQXc3wSLRKXyCL7h7l6FbdFnOvFYOZrvbDKtZP1raVXtJPiq4OWZnYoHpJ0VK+ScuJdkcbKcFVN3AdMfHDXjfZTG80yB4wBCTtGcO04QZzWNViATXH/TYaafZN5WVFokicZ4cBLKaI+Iu42xtz/QDH/HNBsBSHBZ8HFh4FiQKBgQD042y4UxFxLBqprlbvCEozUarOXfMC9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+a6aoGd1sCTkfT2Kyc+LZZavASvepznuqFIOKmvXR3rjDtR58pasR7hHL74HMBcoh4IhVlXv+9DkIjDFcp9dxrkpBsA4lLw+o9ZGcPjv0ZByB7Bm4855z/2UkvgGAwAN+9y3yqmAjSNDlxb6pY3kRr4gKentV15ewHTDr6INvajIOFRA7XWqOQwIDAQAB",
//     // 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
//     // keyType: 'PKCS1',
//     // 设置网关地址，默认是 https://openapi.alipay.com
//     // endpoint: 'https://openapi.alipay.com',
//     gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do"
//   });
//   //实例化支付宝表单
//   let formData = new ALipayFormData();
//   formData.addField("returnUrl", "http://localhost:5173/payment-success")
//   formData.addField("bizContent", {
//     out_trade_no: orderNumber,//订单编号
//     product_code: "FAST_INSTANT_TRADE_PAY",
//     subject: goodsInfo,//付款商品信息
//     body: "234",
//     total_amount: amount//付款金额
//   })
//   //支付宝的第三方接口
//   //alipay.trade.page.pay 打开pc的支付页面
//   //alipay.trade.wap.pay 打开手机的wap页面
//   const result = await alipaySdk.exec('alipay.trade.page.pay', 'GET', {
//     formData
//   });
//   console.log(result)//第三方接口返回值是一个字符串表单信息 前端获取信息即可
//   res.send(result)
// })
// module.exports = router;





// 手机号注册
router.post('/register', async (req, res) => {
  // console.log(132);
  
  try {
    const { phone, password, birthDate, username } = req.body;
    // console.log(username);
    // console.log(phone);
    // console.log(password);
    // console.log(birthDate);
    
    // 验证短信验证码
    // const userWithCode = await User.findOne({ phone });
    // if (!userWithCode?.smsCode || userWithCode.smsCode.code !== smsCode) {
    //   return res.status(400).json({ code: 400, message: '验证码无效' });
    // }

    // 创建用户
    const user = new User({
      username,
      password,
      phone,
      birthDate: new Date(birthDate),
    });

    await user.save();

    // 生成Token
    const { accessToken, refreshToken } = generateTokens({ userId: user._id });
    // console.log(accessToken,refreshToken);
    
    user.refreshToken = refreshToken;
    user.refreshTokenExpires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
    await user.save();

    res.json({
      code: 200,
      data: { accessToken, refreshToken, expiresIn: 900 }
    });
  } catch (err) {
    console.log(err);
    
    res.status(500).json({ code: 500, message: err.message });
  }
});

// 密码登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    const user = await User.findOne({ username }).select('+password');
    
    if (!user || !(await require('bcryptjs').compare(password, user.password))) {
      return res.status(401).json({ code: 401, message: '认证失败' });
    }

    const { accessToken, refreshToken } = generateTokens({ userId: user._id });
    
    user.refreshToken = refreshToken;
    user.refreshTokenExpires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
    await user.save();

    res.json({
      code: 200,
      data: { accessToken, refreshToken, expiresIn: 900 }
    });
  } catch (err) {
    res.status(500).json({ code: 500, message: err.message });
  }
});

// 刷新Token
router.post('/refresh', async (req, res) => {
  try {
    const { refreshToken } = req.body;
    const decoded = verifyToken(refreshToken, true);
    
    const user = await User.findOne({
      _id: decoded.userId,
      refreshToken,
      refreshTokenExpires: { $gt: new Date() }
    });

    if (!user) throw new Error('无效的Refresh Token');

    const newTokens = generateTokens({ userId: user._id });
    
    user.refreshToken = newTokens.refreshToken;
    user.refreshTokenExpires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
    await user.save();

    res.json({
      code: 200,
      data: { ...newTokens, expiresIn: 900 }
    });
  } catch (err) {
    res.status(401).json({ code: 401, message: 'Token刷新失败' });
  }
});

// 获取用户信息
router.get('/profile', async (req, res) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) return res.status(401).json({ code: 401, message: '未授权' });

    const decoded = verifyToken(token);
    const user = await User.findById(decoded.userId).select('-password -refreshToken');

    res.json({ code: 200, data: user });
  } catch (err) {
    res.status(401).json({ code: 401, message: 'Token无效' });
  }
});


module.exports = router;